# Import flask and template operators
import logging
import traceback

from flask import Flask
from flask import jsonify
from flask_basicauth import BasicAuth
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from werkzeug.exceptions import HTTPException

import manager
import config

# Define the WSGI application object
app = Flask(__name__)
# Configurations
app.config.from_object(config)

# Logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app.logger.setLevel(app.config.get('LOG_LEVEL', "DEBUG"))
app.logger.addHandler(handler)

# Define the database object which is imported
# by modules and controllers
db = SQLAlchemy(app, session_options=dict(autocommit=False, autoflush=True))


@app.teardown_request
def teardown_request(exception):
    if exception:
        db.session.rollback()
        db.session.remove()
    db.session.remove()


class Base(db.Model):
    __abstract__ = True

    id = db.Column(db.Integer, primary_key=True)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())


@app.errorhandler(Exception)
def handle_error(e):
    code = 500
    if isinstance(e, HTTPException):
        code = e.code
    app.logger.error(traceback.print_exc())
    return jsonify({
        'code': code,
        'success': False,
        'msg': str(e),
        'data': None
    })


# Build the database:
from manager.app.robot.model import *


def init_database():
    db.init_app(app)
    db.create_all()


# regist robot service proxy
from manager.app.worker.workerController import RobotServiceWorker,Worker
from manager.app.worker.node.DouyinWorker import DouyinWorker

agent = Worker()


def regist_server():
    for device in app.config.get('DEVICES'):
        agent.regist(DouyinWorker(device))


def getWorker():
    return agent


from manager.app.robot.controller import api_robot_bp
from manager.app.device.controller import api_device_bp

# Register blueprint(s)
app.register_blueprint(api_robot_bp)
app.register_blueprint(api_device_bp)



def init_basic_auth():
    if not app.config.get('NO_AUTH'):
        basic_auth = BasicAuth(app)


def initialize():
    init_database()
    regist_server()
    init_basic_auth()
